import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 62536
 * Date: 2023-12-03
 * Time: 13:34
 */
public class MyArrayList implements IList {

    public int[] elem;
    public int usedSize;
    public static final int DEFAULT_CAPACITY = 5;
    public MyArrayList(){
        elem = new int[DEFAULT_CAPACITY];
    }

    @Override
    public void Display() {
        for (int i = 0; i < usedSize; i++) {
            System.out.print(elem[i] +" ");
        }
        System.out.println();
    }

    @Override
    public void add(int data) {
        if(isFull()){
            elem = Arrays.copyOf(elem, 2*elem.length);
        }
        elem[usedSize] = data;
        usedSize++;

    }

    @Override
    public boolean contains(int toFind) {
        for (int i = 0; i < usedSize; i++) {
            if(elem[i] == toFind){
                return true;
            }
        }

        return false;
    }

    @Override
    public int indexOf(int toFind) {
        for (int i = 0; i < usedSize; i++) {
            if(elem[i] == toFind){
                return i;
            }
        }
        return -1;
    }

    @Override
    public int get(int pos) {
        checkPos(pos);
        if(isEmpty()){
            throw new EmptyException("顺序表为空");
        }
        return elem[pos];

    }

    private void checkPos(int pos){
        if(pos < 0 || pos >= usedSize){
            throw new PosException("pos位置不合法 "+ pos);
        }
    }

    @Override
    public void set(int pos, int value) {
        checkPos(pos);
        if(isEmpty()){
            throw new EmptyException("顺序表为空");
        }

        elem[pos] = value;
    }

    @Override
    public void remove(int toRemove) {
        if(isEmpty()){
            throw new EmptyException("顺序表为空，无法删除");
        }
        for (int i = 0; i < usedSize; i++) {
            if(elem[i] == toRemove){
                for(int j = i; j < usedSize - 1; j++){
                    elem[j] = elem[j+1];
                }
            }
        }
        usedSize--;
    }

    @Override
    public int size() {
        return this.usedSize;
    }

    @Override
    public void clear() {
        usedSize = 0;
    }

    @Override
    public void add(int pos, int data) {
        checkPos(pos);
        if(isFull()){
            elem = Arrays.copyOf(elem, 2*elem.length);
        }
        for (int i = usedSize-1; i >= pos ; i--) {
            elem[i+1] = elem[i];
        }
        elem[pos] = data;
        usedSize++;
    }

    @Override
    public boolean isFull() {
        return usedSize == elem.length;
    }

    @Override
    public boolean isEmpty() {
        return usedSize == 0;
    }
}
